<!-- 请假审批 -->
<template>
  <ContainerLayout class="overitem-list">
    <div class="form-container">
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <el-form-item label="用户">
          <el-input v-model="queryForm.user" clearable placeholder="请输入" style="width: 150px" />
        </el-form-item>
        <el-form-item label="部门" v-if="false">
          <el-cascader :options="deptList" :props="deptProps" style="width: 290px" v-model="queryForm.deptIds" collapse-tags clearable />
        </el-form-item>
        <el-form-item label="项目" v-if="false">
          <el-select v-model="queryForm.projectId" placeholder="请选择项目" clearable style="width: 160px">
            <el-option v-for="item in projectList" :key="item.code" :label="`${item.code}-${item.cname}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="queryForm.leaveCategory" placeholder="请选择类型" clearable style="width: 130px">
            <el-option v-for="item in holidayCategoryList" :key="item.dictValue" :label="`${item.dictLabel}`" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.leaveStatus" placeholder="请选择状态" clearable style="width: 130px">
            <el-option v-for="item in leaveStatusOptions" :key="item.value" :label="`${item.label}`" :value="item.value" />
          </el-select>
        </el-form-item>
        <TimeSlotDatePicker label="时段" v-model="queryForm.date" />
        <el-form-item>
          <el-button type="primary" @click="handleClickBtnSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="button-toolbar">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-space wrap :size="20">
            <el-switch v-model="isHistoryData" size="small" active-text="历史" inactive-text="审批" />
            <el-button fixed v-if="false" plain size="small" type="success" @click="handleClickBtnUpdateLeaveStatus(approvalStatusEnum.通过)" :icon="Select">批量通过</el-button>
            <el-button fixed v-if="false" plain size="small" type="danger" @click="handleClickBtnUpdateLeaveStatus(approvalStatusEnum.驳回)" :icon="CloseBold">批量驳回</el-button>
            <ExcelExportButton :headerParams="exportHeaderParams" :table-data="exportTableData" fileName="请假部门审核" />
          </el-space>
        </el-col>
      </el-row>
    </div>
    <div class="table-container">
      <div class="table-wrap" ref="tableWrap">
        <el-table :data="tableData" @selection-change="handleSelectionChange" scrollbar-always-on style="width: 100%" border :height="tableHeight" header-cell-class-name="table-header-row" :row-class-name="tableRowClassName" empty-text="没有数据">
          <el-table-column type="selection" :selectable="selectable" width="55" fixed v-if="false" />
          <el-table-column prop="deptName" label="部门" width="120" fixed v-if="false" />
          <el-table-column prop="userNick" label="姓名" width="150" fixed>
            <template #default="scope">
              {{ scope.row.userNick }}
              <el-popover v-if="scope.row.remark && scope.row.remark.length" :content="scope.row.remark" placement="top">
                <template #reference>
                  <el-text type="danger">
                    <el-icon size="20px"><Warning /></el-icon>
                  </el-text>
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="类型" width="120" fixed>
            <template #default="scope">
              <TextTeg :id="scope.row.leaveCategory * 1" />
            </template>
          </el-table-column>
          <el-table-column label="时段">
            <el-table-column label="开始时间" prop="startTime" width="200" />
            <el-table-column label="结束时间" prop="endTime" width="200" />
          </el-table-column>
          <el-table-column prop="durationTime" label="时长" width="150">
            <template #default="scope">
              <el-text>
                <el-icon>
                  <Clock />
                </el-icon>
                {{ scope.row.durationTime }}
              </el-text>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="150">
            <template #default="scope">
              <el-text type="danger" size="small" v-if="scope.row.remark && scope.row.remark.length">{{ scope.row.remark }}</el-text>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="150">
            <template #default="scope">
              <LeaveStatusTag :status="scope.row.leaveStatus * 1" />
            </template>
          </el-table-column>
          <el-table-column label="流程" width="150">
            <template #default="scope">
              {{ scope.row.leaveProcess }}
            </template>
          </el-table-column>
          <el-table-column prop="reason" label="请假事由" width="350">
            <template #default="scope">
              <div class="remark-content">
                {{ scope.row.reason }}
              </div>
            </template>
          </el-table-column>
          <el-table-column />
          <el-table-column label="审批" width="210" fixed="right" v-if="!isHistoryData">
            <template #default="scope">
              <el-button v-if="false" link type="danger" @click="handleClickBtnDeleteLeave(scope.row)" size="small" :icon="Delete">删除</el-button>
              <el-button link type="success" @click="handleClickBtnUpdateLeaveStatus(approvalStatusEnum.通过, scope.row)" size="small" :icon="Select">通过</el-button>
              <el-button link type="warning" @click="handleClickBtnUpdateLeaveStatus(approvalStatusEnum.驳回, scope.row)" size="small" :icon="CloseBold">驳回</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </ContainerLayout>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, nextTick, watch } from 'vue'
import ContainerLayout from '../layout/ContainerLayout.vue'
import * as utils from '../utils'
import http from '../http'
import { useDeptStore, useProjectssStore, useUsersStore, useHolidayCategoryStore } from '../stores'
import { Refresh, Search, Clock, Select, CloseBold, Delete, Warning } from '@element-plus/icons-vue'
import { leaveStatus, leaveStatusEnum, approvalStatusEnum } from '../definitions/status'
import TextTeg from '../components/TableParts/TextTeg.vue'
import api from '../api'
import TimeSlotDatePicker from '../layout/FormTableLayout/TimeSlotDatePicker.vue'
import ExcelExportButton from '../layout/ButtonToolbar/ExcelExportButton.vue'
import LeaveStatusTag from '../components/Leave/LeaveStatusTag.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const deptList = ref(useDeptStore().getAllState())
const deptProps = ref({ multiple: true, label: 'deptName', value: 'deptId' })
const tableData = ref<any[]>([])
const tableColumnDate = ref<any[]>([])
const tableWrap = ref<HTMLElement | null>(null)
const tableHeight = ref(500)
const multipleSelection = ref<any[]>([])
const holidayCategoryList = ref(useHolidayCategoryStore().getAllState())
const exportTableData = ref<any[]>([])
const exportHeaderParams = [
  { title: '姓名', value: 'userNick', width: 20 },
  { title: '类型', value: 'leaveCategory', width: 20 },
  {
    title: '时段',
    children: [
      { title: '开始时间', value: 'startTime', width: 25 },
      { title: '结束时间', value: 'endTime', width: 25 },
    ],
  },
  { title: '时长', value: 'durationTime', width: 20 },
  { title: '状态', value: 'leaveStatus', width: 25 },
  { title: '请假事由', value: 'remark', width: 30 },
]
const selectable = (row: any) => row.status !== 1

const projectList = ref<Array<{ id: number; code: string; cname: string }>>(useProjectssStore().getAllState() as any)
const queryForm = reactive({
  user: '',
  projectId: null,
  date: [] as Date[],
  deptIds: [] as any[] | number[],
  leaveStatus: null,
  leaveCategory: null,
})

const leaveStatusOptions = ref<any[]>([])
const isHistoryData = ref(false)

Object.keys(leaveStatusEnum).map((value: any) => {
  const label = leaveStatusEnum[value]
  if (typeof label === 'string' && value !== '3') {
    leaveStatusOptions.value.push({
      label,
      value,
    })
  }
})

/**
 * 获取考勤分类列表
 *
 * @returns {Promise<void>}
 */
const getDataList = async () => {
  const [start, end] = queryForm.date
  // 设置 table 列
  tableColumnDate.value = utils.generateDates(start, end)

  const params = {
    // deptId: useUsersStore().getAllState().deptId,
    pageSize: 99999,
    startLeaveDate: utils.formatDate(start, 'yyyy-MM-dd'),
    endLeaveDate: utils.formatDate(end, 'yyyy-MM-dd'),
    approvalUserName: useUsersStore().getAllState().username,
  }
  if (queryForm.leaveCategory) {
    Object.assign(params, { leaveCategory: queryForm.leaveCategory })
  }
  if (queryForm.leaveStatus) {
    Object.assign(params, { leaveStatus: queryForm.leaveStatus })
  }
  if (queryForm.projectId) {
    Object.assign(params, { projectId: queryForm.projectId })
  }
  if (queryForm.user !== '') {
    Object.assign(params, { userName: queryForm.user })
  }

  const funNames = isHistoryData.value ? 'getListHistoryByProcessUser' : 'getListByProcessUser'
  // const rows = await api.Leave[funNames]({
  //   pageSize: 99999,
  //   approvalUserName: useUsersStore().getAllState().username,
  // })
  const rows = await api.Leave[funNames](params)

  tableData.value = rows

  rows.forEach((e: any) => {
    const item = useHolidayCategoryStore().holidayCategory.find((e2: any) => e2.dictValue == e.leaveCategory)
    exportTableData.value.push({
      ...e,
      leaveStatus: leaveStatus[e.leaveStatus][0],
      leaveCategory: item?.dictLabel || '未知',
    })
  })

  nextTick(() => {
    const tableWrapElement = tableWrap.value
    if (tableWrapElement) {
      // 设置表格高度
      tableHeight.value = tableWrapElement.offsetHeight
    }
  })
}
/**
 * 重置表单
 *
 * 重置查询表单的所有字段到初始状态，包括用户、项目ID、日期范围、部门ID数组和时间日志类别
 */
const resetForm = () => {
  tableData.value = []
  const [start, end] = utils.getDateRangeByDate(utils.shortcutsType.本月) as Date[]
  queryForm.user = ''
  queryForm.projectId = null
  queryForm.date = [start, end]
  queryForm.deptIds = [] as string[] | number[]
  queryForm.leaveStatus = null
  handleClickBtnSubmit()
}
/**
 * 处理点击提交按钮的事件
 *
 * 异步调用获取请假分类列表的函数
 */
const handleClickBtnSubmit = async () => {
  await getDataList()
}

watch(
  () => isHistoryData.value,
  async () => {
    await handleClickBtnSubmit()
  }
)

/**
 * 处理点击重置按钮的事件
 *
 * 调用 resetForm 函数重置表单
 */
const handleClickBtnReset = async () => {
  await resetForm()
}

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

/**
 * 更新请假状态处理函数
 *
 * @param status 状态码，表示要更新的请假状态
 * @param row 单条记录对象，可以为null
 * @returns 无返回值
 */
const handleClickBtnUpdateLeaveStatus = async (status: number, row: any | null = null) => {
  let ids: number[] = []
  if (!row) {
    if (multipleSelection.value.length === 0) return ElMessage.warning('请选择要操作的记录')
    ids = multipleSelection.value.map((obj) => obj.id)
  } else {
    ids = [row.id]
  }
  const { leaveCategory, yearNum, monthNum } = row
  const reqArr: any[] = []

  let message = ''
  let flag = false
  if (leaveCategory == 2 && (monthNum >= 5 || yearNum >= 10)) {
    message = '事假！月度大于等于 5 或年度大于 10 天，需要书面申请。'
    flag = true
  } else if (leaveCategory == 3 && yearNum > 15) {
    message = '病假！年度大于 15 天，需要书面申请。'
    flag = true
  }
  switch (status) {
    case approvalStatusEnum.通过:
      if (flag) {
        ElMessageBox.confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            ids.forEach((e) => {
              reqArr.push(api.Leave.updatePassById(e))
            })

            const promisRes = await Promise.all(reqArr)
            if (reqArr.length) {
              const allSuccess = promisRes.every((res) => res.code === 200)
              if (allSuccess) {
                ElMessage.success('操作成功')
                await handleClickBtnSubmit()
              }
            }
          })
          .catch(async () => {})
      } else {
        ids.forEach((e) => {
          reqArr.push(api.Leave.updatePassById(e))
        })

        const promisRes = await Promise.all(reqArr)
        if (reqArr.length) {
          const allSuccess = promisRes.every((res) => res.code === 200)
          if (allSuccess) {
            ElMessage.success('操作成功')
            // 设置通知为未读状态，并刷新页面
            sessionStorage.setItem('LEAVE_ISCHECKED', '0')
            await handleClickBtnSubmit()
          }
        }
      }
      break
    case approvalStatusEnum.驳回:
      ids.forEach((e) => {
        reqArr.push(api.Leave.updateNoPassById(e))
      })

      const promisRes = await Promise.all(reqArr)
      if (reqArr.length) {
        const allSuccess = promisRes.every((res) => res.code === 200)
        if (allSuccess) {
          ElMessage.success('操作成功')
          await handleClickBtnSubmit()
        }
      }
      break
  }
}
const handleClickBtnDeleteLeave = async (row: any) => {
  ElMessageBox.confirm('确定要删除该条数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code } = await http({
        method: 'DELETE',
        path: '/dev-api/oa/leave/' + row.id,
        params: {},
      })
      if (code == 200) {
        ElMessage({
          message: `删除成功！`,
          grouping: true,
          type: 'success',
        })
        await handleClickBtnSubmit()
      }
    })
    .catch(() => {})
}

/**
 * 根据表格行数据生成相应的类名
 *
 * @param {Object} params - 包含表格行数据的对象
 * @param {any} params.row - 表格行数据
 * @returns {string} 根据行数据返回的类名字符串
 */
const tableRowClassName = ({ row }: { row: any }) => {
  // 解构出 row 对象中的 leaveCategory, yearNum, monthNum 属性
  const { leaveCategory, yearNum, monthNum } = row

  let falg = false
  // 判断条件：如果 leaveCategory 等于 2 且 (monthNum 大于等于 5 或 yearNum 大于等于 10)
  if (leaveCategory == 2 && (monthNum >= 5 || yearNum >= 10)) {
    falg = true
  }
  // 判断条件：如果 leaveCategory 等于 3 且 yearNum 大于 15
  else if (leaveCategory == 3 && yearNum > 15) {
    falg = true
  }

  // 如果满足条件，返回 'danger-row'
  if (falg) {
    return 'danger-row'
  }
  // 如果不满足条件，返回空字符串
  else {
    return ''
  }
}

onMounted(async () => {
  nextTick(() => {
    const tableWrapElement = tableWrap.value
    if (tableWrapElement) {
      // 设置表格高度
      tableHeight.value = tableWrapElement.offsetHeight
    }
  })
  await handleClickBtnReset()
})
</script>
<style lang="scss" scoped>
.overitem-list {
  display: flex;
  flex-direction: column;
  .form-container {
    display: flex;
    justify-content: flex-start;
  }
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .table-wrap {
      flex: 1;
    }
  }
  .button-toolbar {
    margin-bottom: 18px;
  }
  .table-header-cell {
    writing-mode: vertical-lr;
  }
  .remark-content {
    width: 100%;
    height: 100%;
    white-space: pre-line;
  }
}
</style>
